package com.zcsy.commons.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

/**  
 * @Project: commons
 * @Title: UploadFile.java
 * @Package com.zcsy.commons.util
 * @Description: 文件的上传处理
 *
 * @author xuwen 13163341028@163.com
 * @date 2015年6月4日 上午10:34:08
 * @Copyright: 2015 武汉中财数元信息有限公司 All rights reserved.
 * @version V1.0  
 */
public class UploadFile {
	
    private static PropertiesUtil propertiesUtil=new PropertiesUtil("config.properties");;
    
    private static String encoding = System.getProperty("file.encoding");
    private static String url= propertiesUtil.getProperty("servername");
    private static String username= propertiesUtil.getProperty("username");
    private static String password= propertiesUtil.getProperty("password");
    
    /**
     * @Description 上传文件值ftp服务器指定目录下
     * @param filename 文件名称
     * @param input 需要上传文件的输入流
     * @param subPath 子目录
     * @return 是否成功
     * @author yuhaichao yhcjhun@foxmail.com
     * @date 2015年7月9日
     */
    public static boolean uploadFile(String filename,InputStream input) {
        boolean result = false;
        try {
        	//连接ftp服务器
        	FTPClient ftpClient = new FTPClient();
        	
        	if(!ftpClient.isConnected()) {
        		ftpClient.connect(url);
        	}
        	ftpClient.login(username, password);
        	ftpClient.setControlEncoding(encoding);
        	ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            //上传文件
            result = ftpClient.storeFile(new String(filename.getBytes(encoding), "UTF-8"), input);
            
            input.close();
            ftpClient.logout();
            ftpClient.disconnect();
            return result;
        }
        catch (Exception e) {
        	return result;
        }
    }
    
    /**
     * @Description 根据当前时间修改文件名称
     * @param fileName 文件名
     * @return 修改后的文件名
     * @author yuhaichao yhcjhun@foxmail.com
     * @date 2015年7月9日
     */
    public static String renameFile(String fileName) {

        String prefix = DateUtils.formatDate(DateUtils.getDate());
        String t_ext = fileName.substring(fileName.lastIndexOf(".") + 1);
        String file_Name = prefix + "." + t_ext;

        return file_Name;
    }

    
    /**
     * @Description 从ftp服务器上下载文件
     * @param remotePath 远程地址
     * @param fileName 文件名
     * @param localPath 下载到本地的地址
     * @return 下载成功或失败true/false
     * @author yuhaichao yhcjhun@foxmail.com
     * @date 2015年7月9日
     */
    public static boolean downFile(String fileName, String localPath) {
        boolean result = false;
        try {
        	//连接ftp服务器
        	FTPClient ftpClient = new FTPClient();
        	if(!ftpClient.isConnected()) {
        		ftpClient.connect(url);
        	}
    		ftpClient.login(username, password);
    		ftpClient.setControlEncoding(encoding);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            
            // 获取文件列表
            FTPFile[] fs = ftpClient.listFiles();
            for (FTPFile ff : fs) {
                if (ff.getName().equals(fileName)) {
                    File localFile = new File(localPath + "/" + ff.getName());
                    OutputStream is = new FileOutputStream(localFile);
                    ftpClient.retrieveFile(ff.getName(), is);
                    is.close();
                }
            }
            ftpClient.disconnect();
            return result = true;
        }
        catch (IOException e) {
            return result;
        }
    }

    /**
     * @Description 获取文件的输入流
     * @param fileName 文件名
     * @return 需要下载的文件的字节流
     * @author yuhaichao yhcjhun@foxmail.com
     * @date 2015年7月9日
     */
    public static InputStream getInputStream(String fileName) {
    	InputStream is = null;
    	try {
    		//连接ftp服务器
        	FTPClient ftpClient = new FTPClient();
        	if(!ftpClient.isConnected()) {
        		ftpClient.connect(url);
        	}
    		ftpClient.login(username, password);
    		ftpClient.setControlEncoding(encoding);
    		ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            
            is = ftpClient.retrieveFileStream(new String(fileName
                    .getBytes("UTF-8"), "iso-8859-1"));
            if (!ftpClient.completePendingCommand()) {  
            	ftpClient.logout();  
            	ftpClient.disconnect();  
            } 
        } catch (IOException e) {
        	return null;
        }
    	return is;
    }
    
    public static void downloadFormHttp(String urlPath, String fileName, HttpServletResponse res) {
    	URL url;
    	InputStream inStream;
    	HttpURLConnection conn;
    	ServletOutputStream out;
    	
    	try {
	    	url = new URL(urlPath);
	    	conn = (HttpURLConnection) url.openConnection();
	    	inStream = conn.getInputStream();
	    	res.setCharacterEncoding("utf-8");
	    	res.setHeader("Content-Disposition","attachment; filename="+URLEncoder.encode(fileName,"utf-8"));
	    	out =res.getOutputStream();  
	    	byte[] buffer = new byte[1204];  
	    	int byteread;
	    	System.out.println(inStream.available());
	    	while ((byteread = inStream.read(buffer)) != -1) {  
	    		out.write(buffer, 0, byteread);  
	    	}  
	    	out.close();
	    	inStream.close();
    	} catch(Exception e) {
    		return;
    	}
    }
}
